package models

import (
	li "container/list"
	"fmt"
	"github.com/samuel/go-zookeeper/zk"
	"strings"
	"time"
)

var con *zk.Conn

func init() {
	hosts := []string{"127.0.0.1"}
	connect, _, err := zk.Connect(hosts, time.Second*5)
	con = connect
	if err != nil {
		fmt.Println(err)
	}

}

func GetAAliveNodesForUpload() (res map[string]string) {
	res = make(map[string]string)
	upload := getAliveNodesForUpload()

	front := upload.Front()

	for front.Next() != nil {
		s := (front.Value).(string)
		data, _, err := con.Get(s)
		if err == nil {
			config := string(data)
			res = configProcess(config)
		} else {
			continue
		}

		front = front.Next()
		//var d = "xxx"

	}

	return
}

func configProcess(conf string) (res map[string]string) {
	split := strings.Split(conf, ",")
	res = make(map[string]string)
	for x := range split {
		i := strings.Split(string(x), ":")
		key := i[0]
		val := i[1]
		res[key] = val
	}

	return
}

func getAliveNodesForDownload() *li.List {
	res := li.New()
	children, _, err := con.Children("downloadNodes")
	if err != nil {
		fmt.Println(err)
	}
	for node := range children {
		res.PushBack(string(node))
	}
	return res
}

func getAliveNodesForUpload() *li.List {
	res := li.New()
	children, _, err := con.Children("uploadNodes")
	if err != nil {
		fmt.Println(err)
	}
	for node := range children {
		res.PushBack(string(node))
	}
	return res
}
